<template>
  <div v-if="chatItem.user_id" class="chat">
    <div class="chat-top">
      <div class="left">
        <img :src="friendData.avatar" />
        <span v-if="chatItem.chatType === 0">{{friendData.nickname}} ({{friendData.username}})</span>
        <span v-else>{{friendData.nickname}} ({{groupUserNumber}})</span>
      </div>
      <div class="right">
        <MoreFilled v-if="chatItem.chatType == 1" @click="openGroupDetail" class="more-icon" />
        <el-dropdown v-else trigger="click" >
          <MoreFilled class="more-icon" />
          <template #dropdown>
            <el-dropdown-menu style="width: 120px;">
              <el-dropdown-item
                style="padding:10px 0px; font-size: 12px;display: flex; justify-content: center;"
              >
                聊天记录
              </el-dropdown-item>
              <el-dropdown-item
                style="padding:10px 0px; font-size: 12px;display: flex; justify-content: center;color: red;"
              >
                清空聊天记录
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
    <div class="chat-body" @mousewheel.one="addScroll">
      <div v-if="loading" class="loading" v-loading="loading" element-loading-text="加载数据中"></div>
      <el-scrollbar
        height="100%"
        @scroll="scroll"
        ref="scrollMenuRef"
      >
        <div ref="innerRef">
          <!-- 单聊 -->
          <div v-if="chatItem.chatType === 0" v-for="item in messageData" class="chat-item">
            <div :class="item.user_id == user_id? 'message-row-right': 'message-row-left'">
              <img :src="item.avatar" class="header-img" />
              <div>
                <div v-if="item.talk_type == 1" class="group-chat-name">{{item.nickname}}</div>
                <div class="message-content">
                  <span></span>
                  <div v-if="item.msg_type == 0">{{item.msg_content}}</div>
                  <div v-if="item.msg_type == 1" @click="gotoLookFile(item)" class="file-area">
                    <div class="left">
                      <div class="name">{{item.msg_content}}</div>
                      <div class="size">50.0k</div>
                    </div>
                    <div class="right">
                      <svg-icon v-if="item.fileType === 'docx' || item.fileType === 'doc'" icon-class="docx" class="icon" />
                      <svg-icon v-if="item.fileType === 'excel' || item.fileType === 'xlsx'" icon-class="excel" class="icon" />
                      <svg-icon v-if="item.fileType === 'pdf'" icon-class="pdf" class="icon" />
                      <svg-icon v-if="item.fileType === 'ppt'" icon-class="ppt" class="icon" />
                      <svg-icon v-if="item.fileType === 'md'" icon-class="md" class="icon" />
                      <svg-icon v-if="item.fileType === 'txt'" icon-class="txt" class="icon" />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <!-- 群聊 -->
           <div v-if="chatItem.chatType === 1" v-for="item in messageData" class="chat-item">
            <div :class="item.user_id == user_id? 'message-row-right': 'message-row-left'">
              <img :src="item.avatar" class="header-img" />
              <div>
                <div class="group-chat-name">{{item.nickname}}</div>
                <div class="message-content">
                  <span></span>
                  <div v-if="item.msg_type == 0">{{item.msg_content}}</div>
                  <div v-if="item.msg_type == 1" @click="gotoLookFile(item)" class="file-area">
                    <div class="left">
                      <div class="name">{{item.msg_content}}</div>
                      <div class="size">50.0k</div>
                    </div>
                    <div class="right">
                      <svg-icon v-if="item.fileType === 'docx' || item.fileType === 'doc'" icon-class="docx" class="icon" />
                      <svg-icon v-if="item.fileType === 'excel' || item.fileType === 'xlsx'" icon-class="excel" class="icon" />
                      <svg-icon v-if="item.fileType === 'pdf'" icon-class="pdf" class="icon" />
                      <svg-icon v-if="item.fileType === 'ppt'" icon-class="ppt" class="icon" />
                      <svg-icon v-if="item.fileType === 'md'" icon-class="md" class="icon" />
                      <svg-icon v-if="item.fileType === 'txt'" icon-class="txt" class="icon" />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-scrollbar>
    </div>
    <div class="chat-bottom">
      <div class="top" style="position: reactive;margin-left: 15px;">
        <div>
          <V3Emoji
            :recent="true"
            :options-name="optionsName"
            @click-emoji="clickEmoji"
            style="position:absolute;"
          />
        </div>
        <svg-icon @click="handleUpload" icon-class="folder" style="margin-left: 50px;" />
        <input
          ref="fileUploadRef"
          type="file"
          style="display:none"
          @change="changeFile($event)"
        />
        <svg-icon icon-class="new" />
      </div>
      <div class="center">
        <el-input
          ref="focusTextarea"
          type="textarea"
          class="input-content"
          v-model="inputContent"
        ></el-input>
      </div>
      <div class="bottom">
        <el-button @click="sendBtn">发送</el-button>
      </div>
    </div>
  </div>
  <div v-else class="noChat">
    <div class="icon">
      <svg-icon icon-class="duihua" class="duihua" />
    </div>
    <div class="content">
      <span style="opacity: .3;">请选择一个会话</span>
    </div>
  </div>
  <el-drawer
    v-model="groupMemberDrawer"
    :with-header="false"
    size="25%"
  >
    <div class="memberDrawer">
      <div class="top">
        <div v-for="item in groupUserList" class="member_item">
          <img :src="item.avatar" />
          <span>{{item.username}}</span>
        </div>
        <div class="member_item">
          <svg-icon icon-class="addMember" class="ope_icon" />
          <span style="font-size: 13px;">添加</span>
        </div>
        <div class="member_item">
          <svg-icon icon-class="reduceMember" class="ope_icon" />
          <span style="font-size: 13px;">减少</span>
        </div>
      </div>
    </div>
  </el-drawer>
</template>

<script setup lang="ts">
import { MoreFilled } from '@element-plus/icons-vue'
import {reactive, ref, onMounted, onUnmounted, watch} from 'vue'
import V3Emoji from 'vue3-emoji'
import 'vue3-emoji/dist/style.css'
import {userController, newsController} from '@/api/index.js'
import {createSocket, sendWSPush, closeConnect} from '@/utils/websocket.js'
import {getCookies} from '@/utils/auth.js'
import {format, formaDate, formatYMD} from '@/utils/time.js'
import {Base64} from 'js-base64'
import {newsStore} from '@/store/index.js'

const user_id = getCookies('user_id')

// 获取pinia中的实例
const newsMainStore = newsStore()

const props = defineProps({
  chatItem: Object
})


const loading = ref(false)
const scrollMenuRef = ref()
const innerRef = ref<HTMLDivElement>()

// 表情包配置
const optionsName = {
  'Smileys & Emotion': '笑脸&表情',
  'Food & Drink': '食物&饮料',
  'Animals & Nature': '动物&自然',
  'Travel & Places': '旅行&地点',
  'People & Body': '人物&身体',
  Objects: '物品',
  Symbols: '符号',
  Flags: '旗帜',
  Activities: '活动'
}
// 单聊请求参数
const params = reactive({
  user_friend: {
    user_friend_id: null,//发送者id,
    username: null, //发送者姓名
    nickname: null, //发送者呢称
    avatar: null //发送头像
  },
  talk_id: null, // 接收者id
  msg_content: null, // 发送消息内容
  msg_date: null, // 发送日期
  talk_type: null, // 对话类型 0 朋友 1群组
  msg_type: null // 0 文字消息  1文件消息
})

// 发送数据
const inputContent = ref('')
const focusTextarea = ref<any>(null)
const fileUploadRef = ref<any>(null)

// 好友数据
const friendData = reactive({
  user_id: null,
  avatar: null,
  username: null,
  nickname: null
})
// 群组成员数据
const groupUserList = ref([])
const groupUserNumber = ref(null)
const groupMemberDrawer = ref(false)
// 获取聊天记录参数
const searchParams = reactive({
  offset: '6',
  friend_id: null,
  max_time: format(new Date(), '-'),
  user_id: parseInt(user_id),
  talk_type: null
})
const minTime = ref(null)

// 聊天记录保存数组
const messageData = ref([])
// 保存传进来的props中的chatItem对象
const chatItemData = ref(null)
// 保存上传文件信息
const fileData = reactive({
  url: null,
  name: null,
  size: null,
  type: null
})


const scrollNum = ref(1)

// 监听传进来的id是否变化
watch(props, (newValue, oldValue) => {
  messageData.value.length = 0
  chatItemData.value = newValue.chatItem
  setTimeout(() => {
    focusTextarea.value.focus()
  }, 0);
  getFriendDetail(newValue.chatItem)
  getSendParams(newValue.chatItem.user_id)
  getChatList(newValue.chatItem)
}, {deep: true})

// 监听消息列表数据是否发生变化
watch(newsMainStore.$state.chatMenu, (newValue, oldValue) => {
  console.log('收到新的消息')
  console.log(newValue)
  console.log(newValue[0])
  let newMessage = null
  if(newValue[0].chatType === 0) {
    newMessage = {
      avatar: newValue[0].avatar,
      user_id: newValue[0].user_id,
      talk_type: newValue[0].chatType,
      nickname: newValue[0].nickname,
      msg_content: newValue[0].msg_content,
      msg_type: newValue[0].msg_type
    }
    messageData.value.push(newMessage)
  } else {
    console.log('进来了群聊这里')
    newMessage = {
      avatar: 'avatar2' in newValue[0] ? newValue[0].avatar2 : newValue[0].avatar,
      friend_id: 'friend_id' in newValue[0] ? newValue[0].friend_id : 0,
      msg_content: newValue[0].msg_content,
      msg_date: newValue[0].msg_date,
      msg_type: newValue[0].msg_type,
      nickname: 'nickname2' in newValue[0] ? newValue[0].nickname2 : newValue[0].nickname,
      talk_type: newValue[0].talk_type,
      user_id: 'user_id2' in newValue[0] ? newValue[0].user_id2 : newValue[0].user_id,
      username: newValue[0].username
    }
    messageData.value.push(newMessage)
  }
  console.log('添加进去的数据==')
  console.log(newMessage)
  
})

// 组件挂载
onMounted(() => {
  // createSocket()
  // getFriendDetail(props.chatItem.user_id)
  // 获取发送消息者信息
  console.log('收到的数据')
  console.log(props.chatItem)
  getSendParams(props.chatItem.user_id)
  getChatList(props.chatItem)
  chatItemData.value = props.chatItem
 
})



// 获取聊天记录
const getChatList = async (item) => {
  searchParams.max_time = formaDate(new Date(), 'YYYY-MM-DD HH:MM:SS'),
  messageData.value.length = 0
  searchParams.friend_id = item.user_id
  searchParams.talk_type = item.chatType
  const res = await newsController.getChatList(searchParams)
  if(res.data.code === 200) {
    if(res.data.data.list) {
       res.data.data.list.forEach(item => {
         if(item.msg_type === 1) {
           if(item.msg_content) {
             item.fileType = item.msg_content.split('.')[1]
           }
         }
          messageData.value.push(item)
      })
    }
    minTime.value = res.data.data.minTime
  }
  console.log('聊天记录==')
  console.log(res)
}

const handleUpload = () => {
  fileUploadRef.value.click()
}

// 刚进入时，没有滚动条，上滑时第一个加载更多数据（后面的上滑加载更多使用element-plus中的组件）
const addScroll = (e) => {
  e = e || window.event
  if(e.wheelDelta) {
    if(messageData.value.length < 5) {
      loading.value = true
      setTimeout(() => {
        loading.value = false
        ElMessage.warning('没有更多数据~~')
      }, 1000)
    } else {
      if(e.wheelDelta > 0 && scrollNum.value==1) {
        loading.value = true
        scrollNum++
        searchParams.max_time = minTime.value
        searchParams.friend_id = props.chatItem.user_id
        searchParams.talk_type = props.chatItem.chatType
        setTimeout(async () => {
          const res = await newsController.getChatList(searchParams)
          if(res.data.code === 200) {
            if(res.data.data.list.length != 0) {
              loading.value = false
              res.data.data.list.forEach(item => {
                messageData.value.unshift(item)
              });
              this.minTime = res.data.data.minTime
            } else {
              ElMessage.warning('没有更多数据~~')
            }
          }
        }, 1000)
      }
    }
  }
}
// element-plus滚动条出现时触发的滚动
const scroll = (event) => {
  if(event.scrollTop === 0) {
    loading.value = true
    if(messageData.value % 5 === 0) {
      loading.value = true
      searchParams.max_time = minTime.value
      searchParams.friend_id = props.chatItem.user_id
      searchParams.talk_type = props.chatItem.chatType
      setTimeout(async () => {
        const res = await newsController.getChatList(searchParams)
        if(res.data.code === 200) {
          loading.value = false
          if(res.data.data.list.length != 0) {
            res.data.data.list.forEach(item => {
              messageData.value.unshift(item)
            });
            this.minTime = res.data.data.minTime
          } else {
            ElMessage.warning('没有更多数据~~')
          }
        }
      },1000)
    } else {
      setTimeout(() => {
        ElMessage.warning('没有更多数据~~')
        loading.value = false
      }, 200)
    }
  }
}

// 发送消息的参数配置
const getSendParams = (id) => {
  const {app_user_id, avatar, nickname, username} = JSON.parse(getCookies('user'))
  params.user_friend.user_friend_id = app_user_id
  params.user_friend.username = username
  params.user_friend.nickname = nickname
  params.user_friend.avatar = avatar
  params.talk_id = id
}

// 根据id获取接收消息用户数据
const getFriendDetail = async (item) => {
  friendData.user_id = null
  friendData.avatar = null
  friendData.nickname = null
  friendData.username= null
  if(item.chatType === 0) {
    friendData.user_id = item.user_id
    friendData.avatar = item.avatar
    friendData.nickname = item.nickname
    friendData.username= item.username
  } else {
    friendData.user_id = item.user_id
    friendData.avatar = item.avatar
    friendData.nickname = item.nickname
    groupUserList.value.length = 0
    const res = await newsController.getGroupUserList({group_id: item.user_id})
    if(res.data.code === 200) {
      groupUserNumber.value = res.data.data.number
      res.data.data.group_member_list.forEach(item => {
        groupUserList.value.push(item)
      });
    }
  }
}

// 打开群组成员详情抽屉
const openGroupDetail = () => {
  groupMemberDrawer.value = true
}

// 发送文件触发事件
const changeFile = async (event) => {
  let file = event.target.files[0]
  fileData.name = file.name
  fileData.type = file.name.split('.')[1] 
  fileData.size = file.size
  console.log('发送文件')
  console.log(event)
  
  let formDate = new FormData();
  formDate.append("file",file)
  const res = await userController.getHeadUrl(formDate)
  console.log('图片上传成')
  console.log(res)
  if(res.data.code == 200) {
    fileData.url = res.data.data.avatar
  }
  sendMessage(1)
}
const gotoLookFile = (item) => {
  window.open(("http://152.136.188.204:9099/resource/" + item.msg_content), "_self")
}

// 点击发送按钮触发
const sendBtn = () => {
  sendMessage(0)
}

// 发送消息
const sendMessage = async (msgType) => {
  console.log('点击发送消息时触发')
  console.log(props.chatItem)
  if(msgType === 0) {
     params.msg_content = inputContent.value
  } else {
    params.msg_content = fileData.name
  }
 
  params.msg_date = format(new Date(), '-')
  params.msg_type = msgType
  if(props.chatItem.chatType === 0) {
    params.talk_type = 0
    let data = {
      type: 1,
      params
    }
  } else {
    params.talk_type = 1
    let data = {
      type: 9,
      params
    }
  }
  console.log('发送的数据')
  console.log(data)
  sendWSPush(data)
  if(props.chatItem.chatType === 0) {
     // 发送消息时，把发送的消息添加到消息聊天数组中
    let newMessage = {
      avatar: data.params.user_friend.avatar,
      friend_id: data.params.talk_id,
      msg_content: data.params.msg_content,
      msg_date: data.params.msg_date,
      msg_type: data.params.msg_type,
      nickname: data.params.user_friend.nickname,
      talk_type: data.params.talk_type,
      user_id: data.params.user_friend.user_friend_id,
      username: data.params.user_friend.username 
    }
    console.log('添加进去的数据==')
    console.log(newMessage)
    messageData.value.push(newMessage)
  }
  


  // getChatList(chatItemData.value)
  // console.log('滚动条对象')
  // console.log(scrollMenuRef.value)
  // scrollMenuRef.value!.setScrollTop(innerRef.value!.clientHeight)
  inputContent.value = ''
}

const clickEmoji = (val: any) => {
  inputContent.value += val
}

// onUnmounted(() => {
//   closeConnect()
// })

</script>

<style lang="scss" scoped>
.chat {
  height: 100%;
  width: 100%;
  &-top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid #DFDFDF;
    height: 7%;
    background-color: #F7F7F7;
    .left {
      display: flex;
      align-items: center;
      margin-left: 30px;
      img {
        width: 40px;
        height: 40px;
      }
      span {
        font-size: 20px;
        margin-left: 15px;
      }
    }
    .right {
      margin-bottom: 20px;
      .more-icon {
        width: 20px;
        height: 20px;
        opacity: .4;
        margin-right: 25px;
        margin-top: 20px;
      }
    }
  }
  &-body {
    height: 68%;
    background-color: #F7F7F7;
    .chat-item {
      margin: 25px;
      .message-row-right {
        display: flex;
        flex-direction: row-reverse;
        .group-chat-name {
          display: none;
        }
        .message-content {
          display: flex;
          align-items: center;
          position: relative;
          margin-right: 15px;
          background-color: #95EC69;
          max-width: 400px;
          border-radius: 6px;
          padding: 10px 10px;
          font-size: 14px;
          letter-spacing: 1px;
          span {
            position: absolute;
            top: 11px;
            right: -17px;
            border: 10px solid transparent;
            border-left-color: #95EC69;
          }
        }
      }
      .message-row-left {
        display: flex;
        .group-chat-name {
          margin-left: 12px;
          font-size: 14px;
          margin-top: -6px;
          margin-bottom: 6px;
          opacity: .5;
        }
        .message-content {
          display: flex;
          align-items: center;
          position: relative;
          margin-left: 15px;
          background-color: #FFFFFF;
          max-width: 400px;
          border-radius: 6px;
          padding: 10px 10px;
          font-size: 14px;
          letter-spacing: 1px;
          span {
            position: absolute;
            left: -17px;
            top: 10px;
            border: 10px solid transparent;
            border-right-color: white;
          }
        }
      }
      .header-img {
        width: 45px;
        height: 45px;
      }
      .file-area {
        display: flex;
        justify-content: space-between;
        width: 220px;
        height: 75px;
        .left {
          width: 75%;
          .name {
            height: 41px;
            font-size: 14px;
            display: -webkit-box;
            overflow: hidden;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
            margin-top: 5px;
          }
          .size {
            margin-top: 5px;
            margin-left: 5px;
            font-size: 13px;
            opacity: .2;
          }
        }
        .right {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 25%;
          height: 100%;
          .icon {
            width: 45px;
            height: 50px;
            margin-bottom: 10px;
          }
        }
      }
    }
  }
  &-bottom {
    height: 25%;
    border-top: 1px solid #D7D7D7;
    background-color: #F7F7F7;
    .top {
      margin-top: 10px;
      display: flex;
      .svg-icon {
        width: 25px;
        height: 25px;
        margin-left: 25px;
      }
    }
    .center {
      margin-left: 20px;
      width: 95%;
      margin-top: 15px;
    }
    .bottom {
      display: flex;
      justify-content: flex-end;
      margin: 0 30px;
      .el-button {
        color: #16D46B;
        padding: 10px 30px;
      }
    }
  }
}
::v-deep .el-textarea__inner {
  height: 90px;
  background-color: #F7F7F7;
  font-size: 14px;
  letter-spacing: 1px;
  border: none;
  outline: none;
  box-shadow: none;
}
.noChat {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  .icon {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 120px;
    height: 120px;
    border-radius: 50%;
    background-color: #F4F5F7;
    .duihua {
      width: 80px;
      height: 80px;
    }
  }
  .content {
    width: 200px;
    line-height: 35px;
    text-align: center;
    border-radius: 20px;
    margin-top: 10px;
    background-color: #F4F5F7;
  }
}
::v-deep .pollup {
  left: -180px;
}
.emoji-item {
  height: 0;
  width: 0;
}
.memberDrawer {
  border: 1px solid red;
  height: 100%;
  .top {
    display: flex;
    flex-wrap: wrap;
    .member_item {
      display: flex;
      justify-content: center;
      flex-direction: column;
      align-items: center;
      width: 55px;
      height: 70px;
      margin: 5px 10px;
      cursor: pointer;
      // border: 1px solid red;
      img {
        width: 40px;
        height: 40px;
        margin-bottom: 8px;
      }
      .ope_icon {
        width: 35px;
        height: 35px;
        margin-bottom: 8px;
        opacity: .5;
      }
      span {
        font-size: 12px;
        // opacity: .7;
      }
    }
  }
}
.loading {
  height: 40px;
  position: relative;
}
::v-deep .el-loading-mask {
  background-color: #F7F7F7;
}
::v-deep .el-loading-spinner .circular {
  width: 20px;
  height: 20px;
}
</style>
